var EventDispatcher = require("./EventDispatcher.js");

function Slider(sel) {
	var self = new EventDispatcher();
	var view = $(sel);
	var textSlider = view;
	var sliderControl = view.find(".text-slider-control");

	var sliderw = textSlider.width();
	sliderControl.on("mousedown", function(e) {
		var ox = e.clientX;
		var conx = sliderControl.css("left");
		conx = parseInt(conx);
		var ty = parseInt(sliderControl.css("left")) / sliderw * 100;
		self.trigger("start", ty);

		$(document).on("mousemove.slider", function(e) {
			var ty = (e.clientX - ox + conx) / sliderw * 100;
			if(ty < 0) {
				ty = 0;
			} else if(ty > 100) {
				ty = 100;
			}
			sliderControl.css("left", ty + "%");

			self.trigger("update", ty);
		});

		$(document).on("mouseleave.slider mouseup.slider", function() {
			$(document).off("mousemove.slider");
			$(document).off("mouseleave.slider mouseup.slider");
			
			self.trigger("complete");
		});
	});
	
	self.setBili = function(bili){
		sliderControl.css("left", bili + "%");
	}
	
	return self;
}

exports = module.exports = Slider;